package com.elaine.service;

import com.elaine.redis.RedisService;
import com.elaine.redis.keymodel.WxPublicTokenKey;
import com.elaine.wxapi.wxpublic.AccessTokenApi;
import com.elaine.wxapi.wxpublic.response.WxApiResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @author wrb
 * @date 2020/4/1 10:38
 */
@Slf4j
@Service
public class WxPbTokenService {

	@Value("${wx.appid}")
	public  String appid;

	@Value("${wx.secret}")
	public  String secret;

	@Autowired
	private RedisService redisService;

	public String getToken() {
		// 获取 redis 中的token
		String token = redisService.get(WxPublicTokenKey.token, appid, String.class);
		if (StringUtils.isEmpty(token)) {
			// redis 中没有则通过 api 获取
			WxApiResult wxApiResult = AccessTokenApi.getToken(appid, secret);
			if (!wxApiResult.isSucceed()) {
				throw new RuntimeException(wxApiResult.getErrorMsg());
			}
			token = wxApiResult.get("access_token");
			// 把 token 放入 redis 中并返回
			boolean b = redisService.set(WxPublicTokenKey.token, appid, token);
			if (!b) {
				log.error("token 放入 redis 中时失败");
			}
		}
		return token;
	}
}
